package org.egedede.commons.ui;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JComponent;
import javax.swing.JPopupMenu;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

public class TreePopupListener extends MouseAdapter {

	private final List<JTree> trees;
	private final Map<Class<?>, JPopupMenu> popups;

	public TreePopupListener() {
		trees = new ArrayList<JTree>();
		popups = new HashMap<Class<?>, JPopupMenu>();
	}

	public void addTree(final JTree t) {
		trees.add(t);
		t.addMouseListener(this);
	}

	@Override
	public void mouseReleased(final MouseEvent e) {
		if (e.isPopupTrigger()) {
			final JTree tree = (JTree) e.getSource();
			final TreePath path = tree.getSelectionPath();
			Object object = path.getLastPathComponent();
			if (object instanceof DefaultMutableTreeNode) {
				object = ((DefaultMutableTreeNode) object).getUserObject();
			}
			final JPopupMenu popup = popups.get(object.getClass());
			popup.show((JComponent) e.getSource(), e.getX(), e.getY());
		}
	}
}
